<template>
  <div class="log-container">
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">日志分析</span>
            <el-select v-model="filterLevel" placeholder="日志级别" clearable>
              <el-option
                v-for="item in logLevels"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                <el-tag :type="getLogLevelType(item.value)" size="small">
                  {{ item.label }}
                </el-tag>
              </el-option>
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
            />
          </div>
          <div class="header-right">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索日志内容"
              style="width: 200px"
              clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredLogData" 
        height="calc(100vh - 200px)" 
        border
        v-loading="loading"
      >
        <el-table-column prop="timestamp" label="时间" width="180" sortable />
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLogLevelType(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="类别" width="150" />
        <el-table-column prop="message" label="消息">
          <template #default="{ row }">
            <div class="message-cell">
              {{ row.message }}
              <el-button 
                v-if="row.details"
                link
                type="primary" 
                @click="showDetails(row)">
                查看详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailsVisible"
      title="日志详情"
      width="60%"
    >
      <pre class="log-details">{{ selectedLog?.details || '无详细信息' }}</pre>
      <template #footer>
        <el-button @click="detailsVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleCopyDetails">
          复制内容
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'

// 日志级别选项
const logLevels = [
  { value: 'DEBUG', label: 'DEBUG' },
  { value: 'INFO', label: 'INFO' },
  { value: 'WARN', label: 'WARN' },
  { value: 'ERROR', label: 'ERROR' }
]

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '最近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    }
  }
]

// 状态变量
const loading = ref(false)
const filterLevel = ref('')
const dateRange = ref(null)
const searchKeyword = ref('')
const detailsVisible = ref(false)
const selectedLog = ref(null)

// 日志数据
const logData = ref([
  {
    timestamp: '2024-01-17 18:30:00',
    level: 'INFO',
    category: '系统',
    message: '系统启动成功'
  },
  {
    timestamp: '2024-01-17 18:30:05',
    level: 'ERROR',
    category: '图片处理',
    message: '图片处理失败: 无法读取文件',
    details: '错误堆栈：\nError: ENOENT: no such file or directory\nat Object.readFileSync...'
  },
  {
    timestamp: '2024-01-17 18:35:00',
    level: 'WARN',
    category: '性能监控',
    message: 'CPU 使用率超过阈值',
    details: 'CPU使用率: 85%\n内存使用率: 70%\n磁盘使用率: 65%'
  }
])

// 获取日志级别对应的标签类型
function getLogLevelType(level) {
  const types = {
    INFO: 'info',
    WARN: 'warning',
    ERROR: 'danger',
    DEBUG: ''
  }
  return types[level] || 'info'
}

// 过滤后的日志数据
const filteredLogData = computed(() => {
  let result = [...logData.value]
  
  // 按级别过滤
  if (filterLevel.value) {
    result = result.filter(log => log.level === filterLevel.value)
  }
  
  // 按日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value
    result = result.filter(log => {
      const timestamp = new Date(log.timestamp)
      return timestamp >= start && timestamp <= end
    })
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(log => 
      log.message.toLowerCase().includes(keyword) ||
      log.category.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

// 刷新日志
async function handleRefresh() {
  loading.value = true
  try {
    // TODO: 从后端获取最新日志
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 导出日志
function handleExport() {
  const data = filteredLogData.value.map(log => ({
    时间: log.timestamp,
    级别: log.level,
    类别: log.category,
    消息: log.message,
    详情: log.details || ''
  }))
  
  // 创建CSV内容
  const headers = ['时间', '级别', '类别', '消息', '详情']
  const csv = [
    headers.join(','),
    ...data.map(row => headers.map(header => `"${row[header]}"`).join(','))
  ].join('\n')
  
  // 创建下载链接
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `日志导出_${new Date().toISOString().split('T')[0]}.csv`
  link.click()
  
  ElMessage.success('导出成功')
}

// 显示日志详情
function showDetails(log) {
  selectedLog.value = log
  detailsVisible.value = true
}

// 复制详情内容
function handleCopyDetails() {
  if (selectedLog.value?.details) {
    navigator.clipboard.writeText(selectedLog.value.details)
    ElMessage.success('已复制到剪贴板')
  }
}
</script>

<style scoped>
.log-container {
  padding: 20px;
  height: 100%;
}

.log-card {
  height: calc(100vh - 100px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin-right: 16px;
}

.message-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-details {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  white-space: pre-wrap;
  font-family: monospace;
  max-height: 400px;
  overflow-y: auto;
}
</style> 